import store from '@/store'
import {getSignature} from '@/api/file'

export function getFileSize(fileByte) { // 计算文件大小
  if (fileByte == '') {
    return ''
  }
  var fileSizeByte = fileByte;
  var fileSizeMsg = "";
  if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
  else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
  else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
  else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) fileSizeMsg = "1GB";
  else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  else fileSizeMsg = "文件超过1TB";
  return fileSizeMsg;
}

export function getParentName(arr, id) {
  arr.forEach(element => {
    if (Array.isArray(element)) {
      getParentName(arr, id)
    } else if (element.id == id) {
      return arr.value
    }
  });
}

export function getHashName(uid) {
  return store.state.user.userInfo.user_id + generateMixed(2) + uid
}

export function formatTime(time) {
  var current = (new Date()).valueOf() / 1000;
  return time > current + 10;//1000*
}

//上传图片OSS
var config = {
  accessid: '',
  policy: '',
  signature: '',
  dir: '',
  host: '', // 上传阿里云地址
  expire: '', // 过期时间戳
  callback: ''
}

export function uploadOss(targetFile,type) {
  return new Promise(getSign)
    .then(resOne => {
      return toOSS(targetFile,type);
    })
    .then(resTwo => {
      return resTwo
    })
    .catch(function (err) {
      return new Error({
        type: 'abort',
        msg: 'error'
      })
    })
}

function getSign(resolve, reject) {
  //签名
  if (formatTime(config.expire)) {//未过期
    resolve('success');
  } else {//过期
    getSignature().then(res => {
      config = res.data;
      resolve('success1');
    }).catch(err => {
      reject(err)
    })
  }
}

function toOSS(file,type) {
  var p = new Promise(function (resolve, reject) {
    let formData = new FormData();
    var name = getHashName(new Date().getTime());
    formData.append('name', name)
    formData.append('key', config.dir + name + "." + file.name.split(".")[1])
    formData.append('policy', config.policy)
    formData.append('OSSAccessKeyId', config.accessid)
    formData.append('success_action_status', '200')
    formData.append('callback', config.callback)
    formData.append('signature', config.signature)
    formData.append("file", file);
    //同名问题
    var index = -1;
    const arr = store.state.common.percent;
    for(var i=0,len=arr.length;i<len;i++){
      const item = arr[i];
      if(item.oldName==file.name){
        index=i;
      }
    }
    if(index!=-1){//同名
      resolve('success1');
    }
    var xhr = new XMLHttpRequest();
    xhr.open("post", config.host, true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
          try {
            store.commit('SET_PERCENT', {name:file.lastModified,title:file.name,percent:0,type:type,oldName:file.name})
            //获取数据
            var result = JSON.parse(xhr.responseText)

            if(result.Status == 'OK') {
              const url = result.url.split('?')[0]
              resolve({
                url: url,
                name: name,
                oldName: file.name,
                type:type,
                fileKey: result.fileKey
              });
            } else {
              reject('上传失败');
            }
          } catch (e) {
            reject(e);
          }
        } else {
          reject(new Error("Request was unsuccessful: " + xhr.statusText));
        }
      }
    }
    xhr.upload.onprogress = function (e) {
      var ev = e || window.event;
      var percent = Math.floor((ev.loaded / ev.total) * 100);
      store.commit('SET_PERCENT',{name:file.lastModified,title:file.name,percent:percent,type:type,oldName:file.name} )
    }
    xhr.send(formData);
    xhr.onabort = function () {
      reject({
        errorType: 'abort_error',
        msg: '拒绝访问'
      });
    }
    xhr.ontimeout = function () {
      reject({
        errorType: 'timeout_error',
        xhr: '上传超时'
      });
    }
    xhr.onerror = function () {
      reject({
        errorType: 'onerror',
        xhr: '上传错误'
      })
    }
  });
  return p;
}
//生成n位随数
function generateMixed(n) {
  var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
    'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  var res = "";
  for (var i = 0; i < n; i++) {
    var id = Math.ceil(Math.random() * 35);
    res += chars[id];
  }
  return res;
}
//获取文件后缀
export function getType(file){
  var filename=file;
  var index1=filename.lastIndexOf(".");
  var index2=filename.length;
  var type=filename.substring(index1,index2);
  return type;
}
